/**
* Copyright (c) 2012-2013 Nokia Corporation. All rights reserved.
* Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation. 
* Oracle and Java are trademarks or registered trademarks of Oracle and/or its
* affiliates. Other product and company names mentioned herein may be trademarks
* or trade names of their respective owners. 
* See LICENSE.TXT for license information.
*/
package com.nokia.example.racer.gestures;

import com.nokia.example.racer.Main;
import com.nokia.mid.ui.gestures.GestureEvent;
import com.nokia.mid.ui.gestures.GestureInteractiveZone;
import com.nokia.mid.ui.gestures.GestureRegistrationManager;

/**
 * Implement gesture support.
 * @see com.nokia.mid.ui.gestures
 */
class GestureProviderImpl
    extends GestureProvider
    implements com.nokia.mid.ui.gestures.GestureListener {

    /*
     * timestamp to measure gesture length (time)
     */
    private long lastTimestamp = 0;

    GestureProviderImpl() {
        // Listen to gesture events
        GestureInteractiveZone giz =
            new GestureInteractiveZone(GestureInteractiveZone.GESTURE_DRAG);

        GestureRegistrationManager.register(Main.getInstance().getGameView(),
            giz);
        GestureRegistrationManager.setListener(Main.getInstance().getGameView(),
            this);
    }

    /**
     * A method that must GestureListener must implement. Handles drag events.
     *
     * @param container
     * @param gestureZone
     * @param gestureEvent
     */
    public void gestureAction(Object container,
        GestureInteractiveZone gestureZone, GestureEvent gestureEvent) {
        switch (gestureEvent.getType()) {
            /*
             * rotate car by dragging
             */
            case GestureInteractiveZone.GESTURE_DRAG:
                long current = System.currentTimeMillis();
                if (lastTimestamp == 0) {
                    lastTimestamp = current;
                }
                /*
                 * if gesture takes over 20 ms time, handle it
                 */
                if ((current - lastTimestamp) > 20) {
                    handleDrag(gestureEvent);
                    lastTimestamp = current;
                }
                break;
        }
    }

    private void handleDrag(GestureEvent event) {
        int startX = event.getStartX();
        int xDistance = event.getDragDistanceX();
        int endX = startX + xDistance;
        xDistance = Math.abs(xDistance);
        /*
         * check if drag was longer than 5 pixels
         */
        if (xDistance > 5) {
            Main.getInstance().getGameView().handleDrag(startX, endX);
        }
    }
}
